import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {BaseComponent} from '../common/base.component';
import {FileUploader} from 'ng2-file-upload';
import {GetLogicService} from './getLogic.service';
import {RealInfoPage, PathInfoPage, PathInfo, GetLogicInfo, AddEvent} from './getLogic';
import {ParamConfig} from '../common/param.config';
import {Http} from '@angular/http';
import 'rxjs/add/operator/toPromise';
import {AddPlaceService} from '../place/place.service';

declare var $: any;

@Component({
  selector: 'app-getlogic',
  templateUrl: './getLogic.component.html'
})
export class GetLogicComponent extends BaseComponent implements OnInit {
  uploader: FileUploader = new FileUploader({
    url: ParamConfig.HTTP_WEB_HOST_URL + 'rbFile/upload?type=3',
    method: 'POST',
    itemAlias: 'file',
    removeAfterUpload: true
  });
  uploader1: FileUploader = new FileUploader({
    url: ParamConfig.HTTP_WEB_HOST_URL + 'rbFile/upload?type=1',
    method: 'POST',
    itemAlias: 'file',
    removeAfterUpload: true
  });
  uploader2: FileUploader = new FileUploader({
    url: ParamConfig.HTTP_WEB_HOST_URL + 'rbFile/upload?type=0',
    method: 'POST',
    itemAlias: 'file',
    removeAfterUpload: true
  });
  name: string; // 基点名称
  sort: string; // 排序
  text: string; // 文字
  private eventId: String = '';
  curPage: Number = 1;
  imgUrl: string;
  fileId: string;
  iconImg: string;
  fileIdVideo: string;
  videoSrc: string;
  fileIdImage: string;
  realInfoPage: RealInfoPage;
  pathInfoPage: PathInfoPage;
  pathInfo: PathInfo[];
  addEvent: AddEvent[];
  curgetLogicInfo: GetLogicInfo;
  image: boolean;
  video: boolean;
  isText: string;
  isImage: string;
  isVideo: string;
  typeTitle: string;
  systemFileTO = [];
  constructor(private addPlaceService: AddPlaceService,
              private http: Http,
              private router: Router,
              private getLogicService: GetLogicService) {
    super();
  }
  ngOnInit() {
    this.curgetLogicInfo = {
      nodeId: '',       // 编号
      name: '',         // 基点名称
      logicName: '',    // 逻辑基点名称
      realNodeId: '',   // 物理基点id
      pathId: '',       // 路径id
      realNodeName: {}, // 物理基点名称
      type: '',         // 动作类型
      sort: '',         // 排序
      text: '',         // 文字内容
      fileIds: [],      // 文件id
      textId: '',       // 文字对应的id
      nodeUrlId: '',    // 图标路径id
      pathName: {},     // 路径名称
      systemFileTO: [{}],    // 文件信息
      eventId: ''
    };
    this.getNodeIdinfo();
    this.queryList();
    this.bbb();
    this.queryListEvent();
  }

  bbb() {
    this.queryListR();
  }

// 获取nodeid
  getNodeIdinfo() {
    this.getLogicService.getNodeIdInfo()
      .then(res => {
        if (res[0]) {
          this.curgetLogicInfo.name = res[1].logicName;
          this.curgetLogicInfo.realNodeId = res[1].realNodeName.nodeId;
          this.curgetLogicInfo.pathId = res[1].pathName.id;
          this.curgetLogicInfo.sort = res[1].sort;
          this.iconImg = res[1].fileUrl;
          this.curgetLogicInfo.eventId = res[1].eventName.id;
        }
      });
  }

// 获取物理基点id
  private queryListR() {
    this.getLogicService.getReal()
      .then(
        page => {
          if (page[0] = true) {
            this.realInfoPage = page[1];
          }
        }
      );
  }

  // 获取路径
  private queryList() {
    this.getLogicService.getPath(this.curPage)
      .then(
        page => {
          this.pathInfoPage = page;
          this.pathInfo = page.pathInfo.datas;
        }
      );
  }

  // 图标
  selectedFileOnChanged(event: any) {
    console.log(event.target.value);
    // 这里是文件选择完成后的操作处理
    this.uploader.queue[0].onSuccess = (response, status, headers) => {
      // 上传文件成功
      if (status === 200) {
        // 上传文件后获取服务器返回的数据
        const tempRes = JSON.parse(response);
        this.fileId = tempRes.systemFileTO.fileId;
      } else {
        // 上传文件后获取服务器返回的数据错误
      }
    };
    this.uploader.queue[0].upload(); // 开始上传
  }

  // 视频
  selectedFileOnChanged1(event: any) {
    console.log(event.target.value);
    // 这里是文件选择完成后的操作处理
    this.uploader1.queue[0].onSuccess = (response, status, headers) => {
      // 上传文件成功
      if (status === 200) {
        // 上传文件后获取服务器返回的数据
        const tempRes = JSON.parse(response);
        this.fileIdVideo = tempRes.systemFileTO.fileId;
        this.videoSrc = tempRes.systemFileTO.fileUrl;
        $('input[type=file]').wrap('<form>').closest('form').get(0).reset();
      } else {
        // 上传文件后获取服务器返回的数据错误
      }
    };
    this.uploader1.queue[0].upload(); // 开始上传
  }

  // 图片
  selectedFileOnChanged2(event: any) {
    console.log(event.target.value);
    // 这里是文件选择完成后的操作处理
    this.uploader2.queue[0].onSuccess = (response, status, headers) => {
      // 上传文件成功
      if (status === 200) {
        // 上传文件后获取服务器返回的数据
        const tempRes = JSON.parse(response);
        this.imgUrl = tempRes.systemFileTO.fileUrl;
        this.fileIdImage = tempRes.systemFileTO.fileId;
      } else {
        // 上传文件后获取服务器返回的数据错误
      }
    };
    this.uploader2.queue[0].upload(); // 开始上传
  }

// 删除图片
  onDeleteImage(value) {
    this.getLogicService.deleteLogicImageinfo(value)
      .then(res => {
        this.imgUrl = '';
        this.getNodeIdinfo();
      });
  }

  private queryListEvent() {
    this.addPlaceService.getEv(this.curPage)
      .then(page => {
          this.addEvent = page.addEvent.datas;
        }
      );
  }

  selEvent(id: string) {
    this.eventId = id;
  }

  // 保存修改
  onLogicEdit() {
    this.getLogicService.updateLogicInfo(this.curgetLogicInfo, this.fileId)
      .then(res => {
          if (res) {
            this.alert.info('修改成功');
            setTimeout(() => {
              this.router.navigate(['/buz/logicAdmin']);
            }, 1000);
           /*setTimeout(function () {
             this.router.navigate(['/buz/logicAdmin'])
           }.bind(this),1000)*/
          } else {
            this.alert.warn('修改失败');
          }
        }
      );
  }

  private handleError(error: any): Promise<[boolean, any]> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject([false, error.toString()]);
  }
}
